<template>
    <div class="container">
        <div class="header" v-if="isPausing" style="width: 84%; text-align: right">
            <a class="re-record" @click="reRecord"><i></i>重新录制</a>
        </div>
        <div class="header" v-else>
            <h2 @click="modalVisible = true">
                {{ store.state.user.clinic_name }} {{ store.state.user.doctor_name }}
            </h2>
            <p class="status" v-if="currentPatientId"><check-circle-filled />患者已扫码并连接</p>
        </div>
        <div class="main">
            <h1 class="title">
                {{ isRecording ? '正在采集' : `${isPausing ? '等待继续采集' : '等待语音采集'}` }}
            </h1>
            <p class="timer" v-if="isRecording">{{ formattedTime }}</p>
            <p class="description">
                {{
                    isRecording
                        ? '若需结束，点击结束按钮'
                        : '当患者进入诊室时，可点击录音按钮开启，结束后将展示对话和总结'
                }}
            </p>
        </div>
        <div :class="['footer', isRecording ? 'recording' : '']">
            <AudioRecorder ref="recorder" :onStop="handleAudioRecordStop">
                <template #start-button="{ startRecording }">
                    <button class="record-btn" @click="startRecording">
                        <audio-filled />
                    </button>
                    <p class="record-text">{{ isPausing ? '继续' : '开始' }}录音</p>
                </template>
            </AudioRecorder>
            <template v-if="isRecording">
                <button class="record-btn stop" @click="clickStopRecordingBtn">
                    <span class="square"></span>
                </button>
                <p class="record-text">停止录音</p>
            </template>
            <div v-if="isRecording" class="recording-bg"></div>
            <p v-if="isPausing" class="pausing-tip">将会继续您的上一段录音</p>
            <BottomModal :visible="modalVisible" @update:visible="modalVisible = $event">
                <template #modal-content>
                    <div class="record-modal-buttons-title">
                        <p class="record-modal-title">患者尚未扫码，请您提醒</p>
                        <p class="record-modal-title">否则将无法接收诊后总结哦</p>
                    </div>
                    <div class="record-modal-buttons-wrap">
                        <a-button type="primary" size="large" @click="continueRecord"
                            >先不停止</a-button
                        >
                        <a-button danger size="large" @click="fuckIWillSendThis"
                            >不发送诊后总结，确认停止</a-button
                        >
                    </div>
                </template>
            </BottomModal>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, onUnmounted } from 'vue';
import { AudioFilled, CheckCircleFilled } from '@ant-design/icons-vue';
import AudioRecorder from '@/components/audioRecorder/index.vue';
import BottomModal from '@/components/modal/BottomModal.vue';
import {
    DoctorInfoGet,
    CreateMedicalRecordPost,
    AdjustVoiceStatusPost,
    VoicePatientGet,
} from '@/apis/user.ts';
import { errorHandler } from '@/utils';
import { message } from 'ant-design-vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';

const router = useRouter();
const store = useStore();
const modalVisible = ref(false);
const recorder = ref(null);
const isRecording = ref(false);
// 暂停：在 isRecording 为 false 的大条件下
const isPausing = ref(false);
const secondsElapsed = ref(0);
const currentPatientId = ref('');
let timerId = null;
let getInfoTimerId = null;

const formattedTime = computed(() => {
    const minutes = Math.floor(secondsElapsed.value / 60)
        .toString()
        .padStart(2, '0');
    const seconds = (secondsElapsed.value % 60).toString().padStart(2, '0');
    return `${minutes}:${seconds}`;
});

const continueRecord = () => {
    modalVisible.value = false;
};

const fuckIWillSendThis = async () => {
    modalVisible.value = false;
    await setRecordStatus('off');
    recorder.value.stopRecording();
};

const clickStopRecordingBtn = async () => {
    if (!currentPatientId.value) {
        modalVisible.value = true;
        return;
    }
    await setRecordStatus('off');
    recorder.value.stopRecording();
};

const reRecord = () => {
    isPausing.value = false;
};

const startTimer = () => {
    stopTimer(); // 防止多个定时器同时运行
    secondsElapsed.value = 0;
    timerId = setInterval(() => {
        secondsElapsed.value++;
    }, 1000);
};

const stopTimer = () => {
    if (timerId) {
        clearInterval(timerId);
        timerId = null;
    }
};

const handleAudioRecordStop = async url => {
    try {
        const { code, message: msg } = await CreateMedicalRecordPost({
            requestBody: {
                cos_url: url,
                patient_id: currentPatientId.value,
            },
        });
        if (code === 200) {
            message.info('病历创建成功');
            router.push({ name: '' });
        } else {
            message.error(msg);
        }
    } catch (error) {
        errorHandler(error);
    }
};

const getUserInfo = async () => {
    try {
        const { code, message: msg, data } = await DoctorInfoGet(undefined);
        if (code === 200) {
            store.dispatch('setUser', data);
        } else {
            message.error(msg);
        }
    } catch (error) {
        errorHandler(error);
    }
};

// "op": "on" / "off"
const setRecordStatus = async status => {
    try {
        const { code, message: msg } = await AdjustVoiceStatusPost({
            requestBody: {
                op: status,
            },
        });
        if (code === 200) {
            console.log(`设置${status}成功`);
        } else {
            message.error(msg);
        }
    } catch (error) {
        errorHandler(error);
    }
};

const startGetInfoTimer = () => {
    getInfoTimerId = setInterval(async () => {
        if (!currentPatientId.value) {
            await getRecordingPatientId();
        } else {
            clearInterval(getInfoTimerId);
        }
    }, 500);
};

const getRecordingPatientId = async () => {
    try {
        const { code, message: msg, data } = await VoicePatientGet(undefined);
        if (code === 200) {
            currentPatientId.value = data?.patient_id || '';
        } else {
            message.error(msg);
        }
    } catch (error) {
        errorHandler(error);
    }
};

const handlePageVisibilityChange = () => {
    if (document.visibilityState === 'hidden') {
        if (isRecording.value) {
            recorder.value.pauseRecording();
            isPausing.value = true;
        }
    }
};

onMounted(() => {
    getUserInfo();
    if (recorder.value) {
        watch(
            () => recorder.value.isRecording,
            async newRecordingStatus => {
                isRecording.value = newRecordingStatus;
                // 录音开始
                if (newRecordingStatus) {
                    startTimer();
                    isPausing.value = false;
                    await setRecordStatus('on');
                    startGetInfoTimer();
                } else {
                    stopTimer();
                    clearInterval(getInfoTimerId);
                }
            },
        );
    }
    document.addEventListener('visibilitychange', handlePageVisibilityChange);
});

onUnmounted(() => {
    stopTimer();
});
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
}

.header {
    margin-top: 45px;
    h2 {
        color: rgb(81, 44, 81);
        font-size: 14px;
        font-weight: 400;
        line-height: 32px;
        letter-spacing: 0px;
        text-align: center;
    }
    .status {
        .anticon {
            color: #52c41a;
            margin-right: 12px;
        }
        color: rgba(0, 0, 0, 0.85);
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        letter-spacing: 0%;
    }
    .re-record {
        cursor: pointer;
        color: rgb(0, 120, 195);
        text-align: right;
        i {
            width: 16px;
            height: 16px;
            display: inline-block;
            vertical-align: middle;
            background: url(~@/assets/img/diagnose/replay.png) no-repeat;
            background-size: cover;
            position: relative;
            top: -1px;
            margin-right: 4px;
        }
    }
}

.main {
    .title {
        margin-top: 200px;
        text-align: center;
    }
    .timer {
        text-align: center;
        color: rgb(0, 120, 195);
        font-size: 32px;
        font-weight: 400;
        line-height: 22px;
        letter-spacing: 0%;
        text-align: center;
        margin-top: 30px;
    }
    .description {
        margin-top: 36px;
        max-width: 250px;
        color: rgb(117, 116, 117);
        font-size: 14px;
        font-weight: 400;
        line-height: 25px;
        letter-spacing: 0px;
        text-align: center;
    }
}

.footer {
    position: relative;
    width: 100%;
    height: 200px;
    margin-top: auto;
    background: rgba(0, 120, 195, 0.1);
    &.recording {
        background: #fff;
    }

    .record-btn {
        position: absolute;
        top: -50px;
        left: 50%;
        transform: translateX(-50%);
        width: 100px;
        height: 100px;
        text-align: center;
        border-radius: 50%;
        background: rgba(199, 0, 11, 1);
        color: #fff;
        border: none;
        &.stop {
            background: rgb(98, 195, 208);
        }
        .anticon {
            font-size: 55px;
        }
        .square {
            display: inline-block;
            width: 30px;
            height: 30px;
            border-radius: 2px;
            background-color: #fff;
            position: relative;
            top: 2px;
        }
    }

    .recording-bg {
        height: 96px;
        width: 100%;
        position: absolute;
        bottom: 0;
        background: url(~@/assets/img/diagnose/record_bg.png) no-repeat;
        background-size: cover;

        /* background-image: url(~@/assets/img/diagnose/record_bg.png);
        background-repeat: repeat-x;
        animation: scrollBackground 5s linear infinite; */
    }
    .record-text {
        position: absolute;
        top: 60px;
        left: 50%;
        transform: translateX(-50%);
        font-size: 16px;
        color: #333;
    }
    .pausing-tip {
        position: absolute;
        bottom: 26px;
        left: 50%;
        transform: translateX(-50%);
        font-size: 16px;
        color: rgb(117, 116, 117);
    }
}

.record-modal-buttons-title {
    p {
        color: rgba(0, 0, 0, 0.65);
        font-size: 20px;
        font-weight: 400;
        line-height: 30px;
        letter-spacing: 0%;
        text-align: center;
    }
}

.record-modal-buttons-wrap {
    .ant-btn {
        margin: 22px auto;
        width: 100%;
        &:last-child {
            margin: 0 auto;
        }
    }
}
</style>
